﻿namespace Jhong.FunMVC
{
    using Microsoft.Owin;
    using System.IO;
    using System.Collections.Generic;
    using System.Text;
    using System;

    public class Response
    {
        private IOwinResponse _owinResponse;

        private IList<byte[]> _outputBuffer = new List<byte[]>();

        internal void PushOutput()
        {
            foreach (var h in this._headers)
                this._owinResponse.Headers.Append(h.Key, h.Value);
            foreach (var o in this._outputBuffer)
                this._owinResponse.Write(o);
        }

        internal void ChangeOwinResponse(Response response)
        {
            this._owinResponse = response._owinResponse;
        }

        public ResponseCookieCollection Cookie
        {
            get
            {
                return this._owinResponse.Cookies;
            }
        }

        public Response(IOwinResponse owinResponse)
        {
            this._owinResponse = owinResponse;
        }

        public string ContentType
        {
            get
            {
                return this._owinResponse.ContentType;
            }
            set
            {
                this._owinResponse.ContentType = value;
            }
        }

        public int ContentLength
        {
            get
            {
                return int.Parse(this._owinResponse.Headers["Content-Length"]);
            }
            set
            {
                this._owinResponse.Headers["Content-Length"] = value.ToString();
            }
        }

        public Stream BodyStream
        {
            get
            {
                return this._owinResponse.Body;
            }
        }

        public void Write(string txt)
        {
            this.Write(Encoding.UTF8.GetBytes(txt));
        }

        public void Write(byte[] data)
        {
            this._outputBuffer.Add(data);
        }

        public void Write(byte[] data, int offset, int count)
        {
            var d2 = new byte[count];
            Array.Copy(data, offset, d2, 0, count);
            this.Write(d2);
        }

        public IDictionary<string, string> Headers
        {
            get
            {
                return this._headers;
            }
        }

        private IDictionary<string, string> _headers = new Dictionary<string, string>();

        public int HttpStatusCode
        {
            set
            {
                this._owinResponse.StatusCode = value;
            }
            get
            {
                return this._owinResponse.StatusCode;
            }
        }
    }
}